package com.yc.testupload.controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * 文件代理Servlet
 * 用于代理转发文件请求，解决跨域和403 Forbidden错误问题
 */
@WebServlet(name = "fileProxyServlet", value = "/api/file-proxy")
public class FileProxyServlet extends HttpServlet {

    private static final Logger logger = LogManager.getLogger(FileProxyServlet.class);
    private static final int BUFFER_SIZE = 4096;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        logger.info("收到文件代理请求");

        // 获取要代理的文件URL
        String fileUrl = request.getParameter("url");
        if (fileUrl == null || fileUrl.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json");
            response.getWriter().write("{\"error\": \"Missing file URL parameter\"}");
            return;
        }

        // URL解码，处理编码的特殊字符
        fileUrl = URLDecoder.decode(fileUrl, StandardCharsets.UTF_8);
        logger.info("代理目标URL: {}", fileUrl);

        // 设置CORS头，允许跨域访问
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");

        try {
            // 创建到目标URL的连接
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(30000);

            // 增强请求头，模拟真实浏览器行为，以绕过403限制
            connection.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36");
            connection.setRequestProperty("Accept",
                    "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8");
            connection.setRequestProperty("Accept-Language",
                    "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("Upgrade-Insecure-Requests", "1");
            connection.setRequestProperty("Cache-Control", "max-age=0");
            connection.setRequestProperty("sec-ch-ua",
                    "\"Chromium\";v=\"118\", \"Google Chrome\";v=\"118\", \"Not=A?Brand\";v=\"99\"");
            connection.setRequestProperty("sec-ch-ua-mobile", "?0");
            connection.setRequestProperty("sec-ch-ua-platform", "\"Windows\"");
            connection.setRequestProperty("Sec-Fetch-Dest", "document");
            connection.setRequestProperty("Sec-Fetch-Mode", "navigate");
            connection.setRequestProperty("Sec-Fetch-Site", "cross-site");
            connection.setRequestProperty("Sec-Fetch-User", "?1");

            // 针对PDF等静态文件的特定设置
            if (fileUrl.toLowerCase().endsWith(".pdf")) {
                connection.setRequestProperty("Accept",
                        "application/pdf, application/x-pdf, application/x-bzpdf, application/x-gzpdf, */*");
            }

            // 允许重定向
            connection.setInstanceFollowRedirects(true);
            connection.setDoOutput(true);
            connection.setDoInput(true);

            // 获取响应码
            int responseCode = connection.getResponseCode();
            logger.info("目标URL响应码: {}", responseCode);

            // 处理403错误 - 尝试使用其他方法获取内容
            if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
                logger.warn("遇到403 Forbidden错误，尝试使用替代方法...");

                // 关闭当前连接
                connection.disconnect();

                // 创建新的连接，使用不同的策略
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(15000);
                connection.setReadTimeout(30000);

                // 使用更简单的请求头，有时反而能绕过某些限制
                connection.setRequestProperty("User-Agent",
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
                connection.setRequestProperty("Accept", "*");
                connection.setRequestProperty("Connection", "keep-alive");
                connection.setRequestProperty("Referer", "https://www.google.com/");
                connection.setInstanceFollowRedirects(true);

                // 再次获取响应
                responseCode = connection.getResponseCode();
                logger.info("替代方法响应码: {}", responseCode);
            }

            // 设置响应状态码
            response.setStatus(responseCode);

            // 复制所有响应头到客户端
            java.util.Map<String, java.util.List<String>> headers = connection.getHeaderFields();
            for (java.util.Map.Entry<String, java.util.List<String>> entry : headers.entrySet()) {
                String headerName = entry.getKey();
                if (headerName != null && !headerName.equalsIgnoreCase("Content-Length") &&
                        !headerName.equalsIgnoreCase("Transfer-Encoding") &&
                        !headerName.equalsIgnoreCase("Connection")) {
                    for (String value : entry.getValue()) {
                        response.addHeader(headerName, value);
                    }
                }
            }

            // 确保设置正确的内容类型
            String contentType = connection.getContentType();
            if (contentType != null) {
                response.setContentType(contentType);
                logger.info("设置内容类型: {}", contentType);
            } else {
                // 根据文件扩展名猜测内容类型
                if (fileUrl.toLowerCase().endsWith(".pdf")) {
                    response.setContentType("application/pdf");
                } else if (fileUrl.toLowerCase().endsWith(".doc") || fileUrl.toLowerCase().endsWith(".docx")) {
                    response.setContentType("application/msword");
                } else if (fileUrl.toLowerCase().endsWith(".xls") || fileUrl.toLowerCase().endsWith(".xlsx")) {
                    response.setContentType("application/vnd.ms-excel");
                }
            }

            // 对于PDF文件，确保设置正确的头部以允许在iframe中预览
            if (fileUrl.toLowerCase().endsWith(".pdf")) {
                response.setHeader("Content-Disposition", "inline; filename=document.pdf");
                response.setHeader("X-Content-Type-Options", "nosniff");
                response.setHeader("X-Frame-Options", "ALLOWALL");
                response.setHeader("Access-Control-Allow-Origin", "*");
            }

            // 获取响应流
            InputStream inputStream;
            if (responseCode >= 200 && responseCode < 300) {
                inputStream = connection.getInputStream();
            } else {
                inputStream = connection.getErrorStream();
                if (inputStream == null) {
                    throw new IOException("服务器返回错误状态码: " + responseCode);
                }
                logger.warn("使用错误流处理非成功响应");
            }

            // 处理gzip压缩的响应
            String contentEncoding = connection.getContentEncoding();
            if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
                inputStream = new java.util.zip.GZIPInputStream(inputStream);
                logger.info("处理gzip压缩内容");
            }

            // 将响应内容写入输出流
            try (OutputStream outStream = response.getOutputStream()) {
                byte[] buffer = new byte[BUFFER_SIZE];
                int bytesRead;
                long totalBytes = 0;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                    totalBytes += bytesRead;
                }
                outStream.flush();
                logger.info("文件内容转发完成，总字节数: {}", totalBytes);
            }

            // 关闭输入流
            inputStream.close();
            connection.disconnect();

        } catch (IOException e) {
            logger.error("文件代理请求失败: {}", e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType("application/json");
            // 使用简单的错误响应，避免复杂的字符串转义
            response.getWriter().write("{\"error\": \"File proxy failed\"}");
        }
    }

    @Override
    protected void doOptions(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 处理预检请求
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        response.setStatus(HttpServletResponse.SC_OK);
    }
}